<?php
namespace My\Controller;

use Utuo\BackgroundController;
use Utuo\Form;
use My\Model\DeliveryModel;
use My\Model\GoodsModel;

class DistributionShopGoodsController extends BackgroundController {
    
    /**
     * 获取多选表单
     *
     * @param string $name
     * @param array $options
     * @param string $default
     * @return string
     */
    protected function getCheckBox($name, $options, $default = array()) {
        $default == null and $default = array();
        !is_array($default) and $default = array($default);
        $ret = array();
        $i = 0;
        foreach ($options as $k => $v) {
            $checked = !is_null($default) && in_array($k, $default) == $k ? " checked='checked'" : '';
            $subject = "<label title='$v'><input type='checkbox' name='$name' id='{$name}_$k' value='$k'$checked> $v</label>";
            $ret[] = str_replace("{:index}", $i, $subject);
            $i++;
        }
        return implode("\n", $ret);
    }
	
	public function _initialize() {
		$this->setControllerTitle("商品管理");
		$this->setActionTitle(array(
				'index' => "商品列表",
				'modify' => "编辑商品",
				'setAttribute' => "设置商品属性",
				'add' => "添加商品",
				'recycle' => "回收站"
		));
		$this->setActionNav('index,add,recycle');
		$this->assign("sid", $this->aid);
		$this->assign('shopConfig', $this->getDistributionShopConfig());
	}
	
	private function getDistributionShopConfig() {
	    $config = D("DistributionShop")->where("cid=%d", $this->aid)->find();
	    if ( !empty($config['currency_config']) ) {
	        $config['currency_config'] = unserialize($config['currency_config']);
	    }
	    return $config;
	}
	
	public function getLists( $is_deleted ) {
	    $name = I('name', '');
		$page = $this->getPage ();
		$pagesize = $this->getPageSize ();
		$d = D ( 'DistributionShopGoods' );
		$params = array();
		$condition = array (
			'cid' => $this->aid,
			'is_deleted' => $is_deleted,
		);
		if ( $name ) {
		    $params['name'] = $name;
		    $condition['name'] = array('like', "%{$name}%");
		}
		$goodsList = $d->where ( $condition )->limit ( $pagesize )->page ( $page )->order ( 'id DESC' )->select ();
		$goodsCount = $d->where ( $condition )->count ();
		foreach ( $goodsList as $k => &$v ) {
			$v['goodsUrl'] = uu($this->aid, 'Home', 'DisShop', 'show', "sid={$this->aid}&id={$v['id']}", true);
		}
		$this->assign("params", $params);
		$this->assign ( 'distributionShopGoodsLists', $goodsList );
		$this->showPage ( $goodsCount, $pagesize, $params );
		$this->display();
	}
	
	/**
	 * 品牌自动完成列表
	 */
	public function brandListAction() {
	    $clsId = I('class_id', 0, 'intval');
	    $name = I("name", "");
	    $d = D("Admin/ProductClass");
	    $data = array();
	    if( !$clsId ) {
	    } else {
	        $brandString = $d->getClassBrand( $clsId ) and $brandString = trim($brandString, ", ");
	        $partnerBrandSql = M("CustomerBrand a")->join("__PRODUCT_BRAND__ b on a.brand=b.id", "LEFT")
                                    	        ->where("a.cid={$this->aid} and a.name like '%{$name}%'")
                                    	        ->field('a.id as brand,case when a.name is not null then a.name when a.name is null then b.name end as brand_name,a.brand as brand_sys')
                                    	        ->select(false); // 合作商品牌
	        $productBrandSql = M("ProductBrand")->where(array("id" => array("exp", " in ($brandString) and id not in ".M("CustomerBrand")->where("cid=%d", $this->aid)->field('brand')->select(false)),
                                    	            "name" => array('like', "%{$name}%"), ))->field('0 as brand,name as brand_name,id as brand_sys')->select(false); // 系统品牌
	        $data = M()->table($partnerBrandSql." a")->union($productBrandSql)->select();
	    }
	    $this->ajaxSuccess("", $data );
	}
	
	
	/**
	 * 由类目获得品牌列表
	 */
	public function updateClassBrandAndEfficiencyAction() {
	    $clsId = I("cls_id", 0, "intval");
	    $selectBrand = I('brandId', 0, 'intval'); // 默认选择的品牌
	    $selectEfficiency = I('efficiencyIds', ""); // 默认选择的功效
	    $selectEfficiency = explode(',', $selectEfficiency);
	    $d = D("Admin/ProductClass");
	    $brandString = $d->getClassBrand( $clsId );
	    $efficiencyString = $d->getClassEfficiency( $clsId );
	    if ( !empty( $brandString ) ) {
	        $brand = M("ProductBrand")->where(array("id" => array("in", $brandString)))->getField("id,name");
	    }
	    if ( !empty( $efficiencyString ) ) {
	        $efficiency = M("ProductEfficiency")->where(array("id" => array("in", $efficiencyString)))->getField("id,name");
	    }
	    $this->ajaxSuccess("", array("brandOptions" => $this->getOption($brand, $selectBrand, '==请选择=='),
	        "efficiencyCheckbox" => $this->getCheckBox("efficiency[{:index}]", $efficiency, $selectEfficiency)));
	}
	
	// 获取子类目
	public function classPostAction() {
	    $id = I('id', 0, 'intval');
	    $d = D('ProductClass');
	    $data = $d->where(array('pid'=>$id, 'is_deleted'=> 0))->order('sort')->select();
	    foreach($data as &$v) $v['isParent'] = true;
	    $this->ajaxSuccess('', $data);
	}
	
	// 获取子栏目
	public function catePostAction() {
	    $id = I('id', 0, 'intval');
	    $d = D('DistributionShopCategory');
	    $data = $d->where(array('pid'=>$id, 'is_deleted'=> 0, "cid"=>$this->aid))->order('sort')->select();
	    foreach($data as &$v) $v['isParent'] = true;
	    $this->ajaxSuccess('', $data);
	}
	
	/**
	 * 添加页
	 */
	public function addAction() {
	    $this->assign("cid", $this->aid);
		$rewardSet = array(
			'0' => '按默认',
			'1' => '自定义',
		);
		$supportCod = array(
			'0' => '否',
			'1' => '是',
		);
		$model = CONTROLLER_NAME;
		$config['supportCodOptions'] =  $this->getOption($supportCod, null, "==请选择==");
		$config['sharingMethodOptions'] = $this->getRadio('reward_set', $rewardSet, 0);
		$config['sharingMethodDealerOptions'] = $this->getRadio('reward_set_dealer', $rewardSet, 0);
		
		/* 运费模板 */
		$deliveryTpl = M("DeliveryTpl")->where(array("cid" => $this->aid))->getField("id,name");
		$deliveryTplOptions = array( '0' => '==不使用运费模板==' );
		foreach ( $deliveryTpl as $k => $v ) $deliveryTplOptions[$k] = $v;
		
		$this->assign("shippingMethods", GoodsModel::$SHIPPING_METHOD);
		$this->assign("deliveryMethods", DeliveryModel::$METHOD);
		$this->assign("deliveryTplOptions", Form::getOption($deliveryTplOptions, 0));
		$this->assign(lcfirst($model), $config);
		$this->display('save');
	}
	
	/**
	 * 修改页
	 */
	public function modifyAction() {
	    $this->assign("cid", $this->aid);
	    $this->assign('donate_on', M('DistributionShop')->where("cid=%d",$this->aid)->getField('donate_on'));
		$rewardSet = array(
			'0' => '按默认',
			'1' => '自定义',
		);
		$supportCod = array(
			'0' => '否',
			'1' => '是',
		);
		$model = CONTROLLER_NAME;
		$config = D($model)->getOneById();
		$config['supportCodOptions'] =  $this->getOption($supportCod, $config['support_cod']*1, "==请选择==");
		$config['images'] and $config['images'] = unserialize($config['images']);
		$config['sharingMethodOptions'] = $this->getRadio('reward_set', $rewardSet, $config['reward_set']*1);
		$config['sharingMethodDealerOptions'] = $this->getRadio('reward_set_dealer', $rewardSet, $config['reward_set_dealer']*1);
		$config['shipping_config'] and $config['shipping_config'] = unserialize($config['shipping_config']);
		
		/*获得类目路径*/
		$classId = $config['class_id'];
		$d = D('Admin/ProductClass');
		$path = "";
		while($classId) {
		    if ( $class = $d->find($classId) ) {
		        $path = $classId.','.$path;
		        $classId = $class['pid']; 
		    } else {
		        break;
		    }
		}
		$config['classPath'] = trim($path, ",");
		
		/*品牌*/
		$brandString = $d->getClassBrand( $config['class_id'] );
		if ( !empty( $brandString ) ) {
		    $brand = M("ProductBrand")->where(array("id" => array("in", $brandString)))->getField("id,name");
		}
		$partnerBrand = M("CustomerBrand a")->join("__PRODUCT_BRAND__ b on a.brand=b.id", "LEFT")->where("a.cid=%d and a.id=%d", $this->aid, $config['brand']*1)->field('a.id as brand,case when a.name is not null then a.name when a.name is null then b.name end as brand_name,a.brand as brand_sys')->find();
		$config['brand'] = $partnerBrand;
		
		/*功效*/
		$efficiencyString = $d->getClassEfficiency( $config['class_id'] );
		if ( !empty( $efficiencyString ) ) {
		    $efficiency = M("ProductEfficiency")->where(array("id" => array("in", $efficiencyString)))->getField("id,name");
		}
		$config['efficiencyCheckbox'] = $this->getCheckBox("efficiency[{:index}]", $efficiency, explode(',', $config['efficiency']));
		
		/*获得栏目路径*/
		$cateId = $config['cate_id'];
		$d = D('DistributionShopCategory');
		$path = "";
		while($cateId) { 
		    if ( $cate = $d->find($cateId) ) {
		        $path = $cateId.','.$path;
		        $cateId = $cate['pid']; 
		    } else {
		        break;
		    }
		}
		$config['catePath'] = trim($path, ",");
		
		/* 运费模板 */
		$deliveryTpl = M("DeliveryTpl")->where(array("cid" => $this->aid))->getField("id,name");
		$deliveryTplOptions = array( '0' => '==不使用运费模板==' );
		foreach ( $deliveryTpl as $k => $v ) $deliveryTplOptions[$k] = $v;
		
		$this->assign("shippingMethods", GoodsModel::$SHIPPING_METHOD);
		$this->assign("deliveryMethods", DeliveryModel::$METHOD);
		$this->assign("deliveryTplOptions", Form::getOption($deliveryTplOptions, $config['shipping_tpl_id'] ));
		$this->assign(lcfirst($model), $config);
		$this->display("save");
	}
	
	public function setAttributeAction() {
		$model = CONTROLLER_NAME;
		$config = D($model)->getOneById();
		if ( !$config['attrs_cfg'] ) {
			$config['attrs_cfg'] = array();
		} else {
			$config['attrs_cfg'] = unserialize($config['attrs_cfg']);
		}
		$attrNames = array_keys($config['attrs_cfg']) or $attrNames = array();
		$this->assign("attrNames", json_encode($attrNames));
		$this->assign("attrJson", json_encode($config['attrs_cfg']));
		$this->assign(lcfirst($model), $config);
		$this->display();
	}
	
	/*
	*	分佣页
	*/
	public function fenchengAction() {
			$this->assign("cid", $this->aid);
	    $this->assign('donate_on', M('DistributionShop')->where("cid=%d",$this->aid)->getField('donate_on'));
		$rewardSet = array(
			'0' => '按默认',
			'1' => '自定义',
		);
		$supportCod = array(
			'0' => '否',
			'1' => '是',
		);
		$model = CONTROLLER_NAME;
		$config = D($model)->getOneById();
		$config['supportCodOptions'] =  $this->getOption($supportCod, $config['support_cod']*1, "==请选择==");
		$config['images'] and $config['images'] = unserialize($config['images']);
		$config['sharingMethodOptions'] = $this->getRadio('reward_set', $rewardSet, $config['reward_set']*1);
		$config['sharingMethodDealerOptions'] = $this->getRadio('reward_set_dealer', $rewardSet, $config['reward_set_dealer']*1);
		$config['shipping_config'] and $config['shipping_config'] = unserialize($config['shipping_config']);
	
		$this->assign("shippingMethods", GoodsModel::$SHIPPING_METHOD);
		$this->assign("deliveryMethods", DeliveryModel::$METHOD);
		$this->assign(lcfirst($model), $config);
		$this->display();
	}
	
	
	public function savesAction() {
	//dump($_POST);die;
		$rewardPercent = I("reward_percent");
		$baseLevels = I("base_levels");
		if( empty($baseLevels) ) {
			$_POST['reward_percent'] = "";
		} else {
			if ( array_sum(explode(':', $rewardPercent)) != 100 ) {
				$this->ajaxError('基础佣金分成比例之和必须等于100%');
			}
		}
		
		$requiredSubscribe = I("buy_required_subscribe", 0);
		$_POST['buy_required_subscribe'] = $requiredSubscribe ? true : false;
		
		$requiredSubscribe = I("discount_open", 0);
		$_POST['discount_open'] = $requiredSubscribe ? true : false;
		
		parent::savesAction();
	}
	
	public function setAttributePostAction() {
		$model = D("DistributionShopGoods");
		if ($model->create()) {
			!$model->attrs_cfg and $model->attrs_cfg = null;
			if (false !== $model->save()) {
				$this->ajaxSuccess("修改成功！");
			} else {
				$this->ajaxError("修改失败！");
			}
		} else {
			$this->ajaxError($model->getError());
		}
	}
	
	public function setSortAction() {
		$id = I('id', 0, 'intval');
		$sort = I('sort', 0, 'intval');
		M('DistributionShopGoods')->where(array('id'=>$id, 'cid'=>$this->aid))->setField('sort', $sort);
	}
	
}
